package cn.sciento.farm.devicemanager.gateway.downlink.service;

import cn.sciento.farm.devicemanager.common.constant.ResultConstant;
import cn.sciento.farm.devicemanager.gateway.downlink.service.impl.MqttSendService;
import cn.sciento.farm.devicemanager.gateway.model.downlink.AbstractBlockData;
import cn.sciento.farm.devicemanager.gateway.model.downlink.DownLinkResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author wumu
 * @version V1.0
 * @date 4/17/18
 * @time 10:05 AM
 */
@Service
public class MqttBlockedSendManager {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    MqttSendService defaultSendService;

    private final static int DEFAULT_TIME_OUT = 20 * 1000;

    public DownLinkResult send(AbstractBlockData abstractBlockData) {
        return send(abstractBlockData, DEFAULT_TIME_OUT);
    }

    public DownLinkResult send(AbstractBlockData abstractBlockData, int timeout) {
        String id = abstractBlockData.generateId();
        if (MqttCallBackFuture.futurePool.get(id) != null) {
            DownLinkResult result = new DownLinkResult();
            result.setCode(ResultConstant.SWITCH_DOUBLE_WARN.getCode());
            return result;
        }

        try {
            abstractBlockData.setBlockId(id);
            MqttCallBackFuture mqttCallBackFuture = new MqttCallBackFuture(abstractBlockData);
            defaultSendService.send(abstractBlockData.generate());
            return mqttCallBackFuture.get(timeout);
        } finally {
            MqttCallBackFuture.futurePool.remove(abstractBlockData.getBlockId());
        }
//        return ResultConstant.SWITCH_TIMEOUT.getCode();
    }



}
